﻿using Abp.Runtime.Session;
using Castle.DynamicProxy;
using NetCore.CustomAttributes;
using NetCore.Locks;
using System.Reflection;
using System.Threading.Tasks;

namespace NetCore.Aop
{
    /// <summary>
    /// 允许依赖注入的缓存锁拦截器
    /// </summary>
    public class CacheLockInterceptor : IInterceptor
    {
        public IAbpSession AbpSession { get; set; }
        public UserCacheLockAttribute LockAttribute { get; set; }
        private readonly ILock _lock;
        public CacheLockInterceptor(ILock @lock)
        {
            _lock = @lock;
        }

        public void Intercept(IInvocation invocation)
        {
            LockAttribute = invocation.MethodInvocationTarget.GetCustomAttribute<UserCacheLockAttribute>();
            if (AbpSession == null || LockAttribute == null)
            {
                invocation.Proceed();
            }
            else
            {
                if (IsAsyncMethod(invocation.Method))
                {
                    InterceptAsync(invocation);
                }
                else
                {
                    InterceptSync(invocation);
                }
            }
        }
        public static bool IsAsyncMethod(MethodInfo method)
        {
            return method.ReturnType == typeof(Task) ||
                   (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>));
        }
        private void InterceptAsync(IInvocation invocation)
        {
            var operationName = LockAttribute.OperationName;
            if (string.IsNullOrEmpty(operationName))
            {
                operationName = invocation.Method.Name;
            }
            var userLock = new UserLock(_lock, AbpSession.UserId, operationName, LockAttribute.Expiration)
                .CheckLock();
            invocation.Proceed();//业务逻辑
            ((Task)invocation.ReturnValue).ContinueWith(task => { userLock.Dispose(); });
        }

        private void InterceptSync(IInvocation invocation)
        {
            var operationName = LockAttribute.OperationName;
            if (string.IsNullOrEmpty(operationName))
            {
                operationName = invocation.Method.Name;
            }

            using (new UserLock(_lock, AbpSession.UserId, operationName, LockAttribute.Expiration).CheckLock())
            {
                invocation.Proceed();
            }
        }

    }
}
